package conchmusic.conchmusicclient.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;


import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.Comment;

import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.pojo.User;
import conchmusic.conchmusicclient.util.AddCommentCommand;
import conchmusic.conchmusicclient.util.GetCommentCommand;
import conchmusic.conchmusicclient.util.Invoker;
import conchmusic.conchmusicclient.util.JsonBuilder;
import conchmusic.conchmusicclient.util.JsonParser;


public class CommentActivity extends AppCompatActivity {
    private ListView lv;
    private List<Comment> commentList;
    private TextView tv;
    private ImageView iv;
    private int songId;
    private String commentJson;
    private Invoker invoker;
    private Handler handler;
    private Handler handlerRes;
    private JsonParser jsonParser;
    private EditText editText;
    private MyDBHelp dbHelp=new MyDBHelp(this,"demon",null,1);
    private ClientControl clientControl=new ClientControl(dbHelp);
    private Song song;
    private User user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);

        int localSongId=getIntent().getIntExtra("localSongId",0);
        song=clientControl.findSong(localSongId);
        songId=song.getSongId();

        commentList=new ArrayList<>();
        lv=(ListView)findViewById(R.id.listview);
        tv=(TextView)findViewById(R.id.commentTV);
        iv=(ImageView)findViewById(R.id.commentIV);
        editText=(EditText)findViewById(R.id.commentET);
        jsonParser=new JsonParser();

        tv.setText(song.getTitle());
        try {
            Bitmap bitmap= BitmapFactory.decodeFile(song.getLocalPictureUrl());
            iv.setImageBitmap(bitmap);
        } catch (Exception e) {

        }

        //打开activity时刷新评论
        freshComment();
        user=clientControl.Login();


        //获取评论列表
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String commentJsonRe=msg.getData().getString("commentJson");
                try {
                    commentList= jsonParser.parseComments(commentJsonRe);
                    SimpleAdapter adapter=new SimpleAdapter(CommentActivity.this.getApplicationContext(),getData(commentList),R.layout.comment_adapter,new String[]{"name","date","comment"},new int[]{R.id.commentName,R.id.commentDate,R.id.comment});
                    lv.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        handlerRes=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String commentResult=msg.getData().getString("commentResult");
                String type="";
                try {
                    type=jsonParser.typeOf(commentResult);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if(type.equals("validInfo")){
                    freshComment();
                }else {
                    Toast.makeText(CommentActivity.this.getApplicationContext(),"failed to commit",Toast.LENGTH_SHORT).show();
                }
            }
        };
    }

    private List<Map<String,Object>> getData(List<Comment> comments){
        List<Map<String, Object>> list = new ArrayList<>();
        if(comments==null){
            Toast.makeText(getApplicationContext(), "请输入评论", Toast.LENGTH_LONG).show();
            return null;
        }
        for(int i=0;i<comments.size();i++){
            Map<String, Object> map = new HashMap<>();
            map.put("name",comments.get(i).getUserName());
            map.put("date",comments.get(i).getCreatedTime());
            map.put("comment",comments.get(i).getCommentBody());
            list.add(map);
        }
        return list;
    }

    public void commentCommit(View view) {
        String commentBody="";
        commentBody=editText.getText().toString();
        if(user!=null){
            commit(commentBody);
        }else {
            Toast.makeText(this, "请先登录！", Toast.LENGTH_SHORT).show();
        }
        editText.setText("");
    }



    public void commentFresh(View view) {
        freshComment();
    }

    //发表评论功能
    public void commit(String commentBody){
        Comment comment=new Comment();
        comment.setCommentBody(commentBody);
        comment.setSongId(songId);
        comment.setUserId(user.getUserId());
        JsonBuilder jsonBuilder=new JsonBuilder();
        String commentJson="";
        try {
            commentJson=jsonBuilder.buildComment(comment);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        AddCommentCommand addCommentCommand=new AddCommentCommand(getResources(),commentJson);
        invoker.setTransferCommand(addCommentCommand);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String commentResult=invoker.action();
                Log.i("commentResult",commentResult+"...");
                Message msg=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("commentResult",commentResult);
                msg.setData(bundle);
                handlerRes.sendMessage(msg);
            }
        }).start();


    }
    //刷新评论列表
    public void freshComment(){
        invoker=new Invoker();
        GetCommentCommand getCommentCommand=new GetCommentCommand(getResources(),songId);
        invoker.setTransferCommand(getCommentCommand);
        new Thread(new Runnable() {
            @Override
            public void run() {
                commentJson=invoker.action();
                Log.i("commentJson",commentJson+"...");
                Message msg=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("commentJson",commentJson);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        }).start();
    }
}
